/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.summary.service.impl;

import me.zhengjie.modules.summary.domain.Record;
import me.zhengjie.modules.summary.domain.RecordSub;
import me.zhengjie.modules.summary.service.RecordSubService;
import me.zhengjie.modules.summary.service.dto.RecordSubDto;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.summary.repository.RecordRepository;
import me.zhengjie.modules.summary.service.RecordService;
import me.zhengjie.modules.summary.service.dto.RecordDto;
import me.zhengjie.modules.summary.service.dto.RecordQueryCriteria;
import me.zhengjie.modules.summary.service.mapstruct.RecordMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author yyj
* @date 2022-12-26
**/
@Service
@RequiredArgsConstructor
public class RecordServiceImpl implements RecordService {

    private final RecordRepository recordRepository;
    private final RecordMapper recordMapper;

    @Resource
    private RecordSubService recordSubService;
    @Override
    public Map<String,Object> queryAll(RecordQueryCriteria criteria, Pageable pageable){
        Page<Record> page = recordRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(recordMapper::toDto));
    }

    @Override
    public List<RecordDto> queryAll(RecordQueryCriteria criteria){
        return recordMapper.toDto(recordRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public RecordDto findById(String id) {
        Record record = recordRepository.findById(id).orElseGet(Record::new);
        ValidationUtil.isNull(record.getId(),"Record","id",id);
        return recordMapper.toDto(record);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RecordDto create(Record resources) {
        resources.setId(IdUtil.simpleUUID());
        resources.getRecordSubs().forEach(res->{
            res.setCreateTime(new Timestamp(new Date().getTime()));
            res.setRecordId(resources.getId());
            recordSubService.create(res);
        });

        return recordMapper.toDto(recordRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Record resources) {
        Record record = recordRepository.findById(resources.getId()).orElseGet(Record::new);
        ValidationUtil.isNull( record.getId(),"Record","id",resources.getId());
        // 处理演练项目数据前先删除待删除的演练项目
        if (resources.getProjectIdList() != null && resources.getProjectIdList().size() > 0) {
            recordSubService.deleteAll(resources.getProjectIdList().toArray(new String[0]));
        }
        resources.getRecordSubs().forEach(item->{
            if(item.getId() == null){
                item.setRecordId(resources.getId());
                recordSubService.create(item);
            }else{
                recordSubService.update(item);
            }
        });
        record.copy(resources);
        recordRepository.save(record);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            recordRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<RecordDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (RecordDto record : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("名称", record.getName());
            map.put("子名称", "无");
            map.put("类型", record.getType());
            double sum = record.getRecordSubs().stream().map(RecordSub::getContent).mapToDouble(Double::parseDouble)// 类型转换为浮点数
//                    .mapToInt(Integer::parseInt)
                    .sum();// 求和
            map.put("总和", sum);
            map.put("内容", "无");
            map.put("备注", "无");
            list.add(map);
            for (RecordSub recordSub : record.getRecordSubs()) {
                Map<String,Object> map1 = new LinkedHashMap<>();
                map1.put("名称", "");
                map1.put("子名称", recordSub.getName());
                map1.put("类型", "");
                map1.put("总和", "0");
                map1.put("内容", recordSub.getContent());
                map1.put("备注", recordSub.getRemark());
                list.add(map1);
            }
        }
        FileUtil.downloadExcel(list, response);
    }
}